from ..models.house import House
from ..extensions import db
from ..utils.response import success, error, pagination

def create_house(data):
    """创建房屋"""
    # 验证必填字段
    if not data.get('name'):
        return error('户号标识不能为空', 400)
    
    # 验证户号唯一性
    name = data.get('name')
    existing_house = House.query.filter_by(name=name).first()
    if existing_house:
        return error('户号已存在', 400)
    
    # 创建房屋
    house = House(
        name=name
    )
    
    try:
        db.session.add(house)
        db.session.commit()
        return success(house.to_dict(), '创建成功')
    except Exception as e:
        db.session.rollback()
        return error('创建失败', 500)

def get_houses(data):
    """获取房屋列表，支持按户号筛选，支持分页"""
    query = House.query
    
    # 按户号筛选
    if data.get('name'):
        query = query.filter(House.name.like(f"%{data['name']}%"))
    
    # 计算总数
    total = query.count()
    
    # 按创建时间倒序排序
    query = query.order_by(House.created_at.desc())
    
    # 获取分页参数
    page = int(data.get('page', 1))
    page_size = int(data.get('page_size', 10))
    
    # 处理无效的分页参数
    if page < 1:
        page = 1
    if page_size < 1:
        page_size = 10
    elif page_size > 100:
        page_size = 100  # 限制最大每页记录数
    
    # 计算偏移量
    offset = (page - 1) * page_size
    
    # 获取分页数据
    houses = query.offset(offset).limit(page_size).all()
    
    # 返回分页数据
    return pagination(
        items=[house.to_dict() for house in houses],
        total=total,
        msg='获取成功',
        code=200
    )

def get_house(data):
    """获取单个房屋信息"""
    # 获取房屋ID
    house_id = data.get('id')
    if not house_id:
        return error('房屋ID不能为空', 400)
    
    # 查找房屋
    house = House.query.get(house_id)
    if not house:
        return error('房屋不存在', 404)
    
    return success(house.to_dict(), '获取成功')

def update_house(data):
    """更新房屋信息"""
    # 获取房屋ID
    house_id = data.get('id')
    if not house_id:
        return error('房屋ID不能为空', 400)
    
    # 查找房屋
    house = House.query.get(house_id)
    if not house:
        return error('房屋不存在', 404)
    
    # 更新户号
    if 'name' in data:
        if not data['name']:
            return error('户号标识不能为空', 400)
        # 检查户号唯一性
        existing_house = House.query.filter_by(name=data['name']).first()
        if existing_house and existing_house.id != house_id:
            return error('户号已存在', 400)
        house.name = data['name']
    
    try:
        db.session.commit()
        return success(house.to_dict(), '更新成功')
    except Exception as e:
        db.session.rollback()
        return error('更新失败', 500)

def delete_house(data):
    """删除房屋"""
    # 获取房屋ID
    house_id = data.get('id')
    if not house_id:
        return error('房屋ID不能为空', 400)
    
    # 查找房屋
    house = House.query.get(house_id)
    if not house:
        return error('房屋不存在', 404)
    
    try:
        db.session.delete(house)
        db.session.commit()
        return success(None, '删除成功')
    except Exception as e:
        db.session.rollback()
        return error('删除失败', 500)